<template>
  <q-splitter :limits="[0, 100]" v-model="splitterModel" :horizontal="$q.screen.xs">
    <template v-slot:before>
      <catalog ref="catalog" @selected="selectCatalog" />
    </template>

    <template v-slot:separator v-if="!$q.screen.xs">
      <q-avatar color="primary" text-color="white" size="40px" icon="drag_indicator" />
    </template>

    <template v-slot:after>
      <searchArea :fieldlist="searchList" @search="search" @reset="search" btnSize="sm" />
      <q-table
        :grid="grid"
        :rows="data"
        :columns="columns"
        row-key="id"
        v-model:pagination="pagination"
        :loading="loading"
        :filter="filter"
        :rows-per-page-options="[25, 50, 100, 0]"
        @request="onRequest"
        binary-state-sort
        :visible-columns="visibleColumns"
        :style="$q.screen.xs ? '' : 'max-height: calc(100vh - 100px)'"
        class="my-sticky-virtscroll-table"
      >
        <template v-slot:top>
          <div class="q-table__title q-mr-md">{{ modelLabel }}</div>
          <q-select
            label="选择显示列"
            v-model="visibleColumns"
            multiple
            borderless
            dense
            options-dense
            :display-value="visibleColumns.length + '/' + columns.length + '列'"
            emit-value
            map-options
            :options="columns"
            option-value="name"
            :style="{'min-width': $q.screen.xs ? '100px' : '150px'}"
          />
          <q-btn :icon="grid ? 'table_view' : 'grid_view'" dense @click="grid = !grid" />
          <q-space />
          <div class="q-gutter-x-sm">
            <q-btn label="新增" color="primary" icon="add" :dense="$q.screen.xs" @click="goDetailEx(-1)" v-if="canAdd">
              <q-tooltip>新增{{ modelLabel }}</q-tooltip>
            </q-btn>

            <q-btn label="导入" color="secondary" icon="cloud_upload" :dense="$q.screen.xs" @click="doImport" v-if="canAdd">
              <q-tooltip>导入{{ modelLabel }}</q-tooltip>
            </q-btn>
          </div>
        </template>

        <template v-slot:body-cell-operate="props">
          <q-td :props="props">
            <q-btn color="secondary" :label="canEdit || props.row._owner ? '修改' : '查看'" dense @click="goDetailEx(props.row.id)">
              <q-tooltip>修改{{ modelLabe }}</q-tooltip>
            </q-btn>
            <q-btn color="info" label="克隆" dense @click="goDetailEx('-1,'+props.row.id)" v-if="canAdd">
              <q-tooltip>克隆</q-tooltip>
            </q-btn>
            <q-btn color="grey" flat label="删除" dense @click="deleteDetail(props.row.id)" v-if="canEdit|| props.row._owner">
              <q-tooltip>删除{{ modelLabel }}</q-tooltip>
            </q-btn>
          </q-td>
        </template>

        <template v-slot:body-cell-material_name="props">
          <q-td :props="props">
            <div class="flex items-center no-wrap">
              <viewer :images="props.row.default_image" class="flex">
                <template #default="scope">
                  <div class="image-box-xs" v-for="img in scope.images" :key="img.thumb">
                    <img class="fit-thumb" :src="img.image" :data-src="img.image" />
                  </div>
                </template>
              </viewer>
              {{ props.value }}
            </div>
          </q-td>
        </template>

        <template v-slot:body-cell-recommend="props">
          <q-td :props="props">
            <q-badge color="blue" v-if="props.value">
              推荐
            </q-badge>
          </q-td>
        </template>

        <template v-slot:body-cell-remark="props">
          <q-td :props="props">
            <div style="max-width: 300px;" class="ellipsis" @click="confirmBox('详情', props.value)">
              {{ props.value }}
              <q-tooltip>点击查看详情</q-tooltip>
            </div>
          </q-td>
        </template>

        <template v-slot:item="props">
          <q-list dense class="fit shadow-1 q-mb-md q-py-md">
            <q-item v-for="col in props.cols.filter(col => !col.delay || props.row._hidden)" :key="col.name">
              <q-item-section class="text-grey-8">
                <q-item-label>{{ col.label }}</q-item-label>
              </q-item-section>
              <q-item-section>
                <div v-if="col.name === 'operate'">
                  <q-btn color="secondary" :label="canEdit || props.row._owner ? '修改' : '查看'" @click="goDetailEx(props.row.id)"  v-if="canEdit|| props.row._owner" />
                  <q-btn color="info" label="克隆" @click="goDetailEx('-1,'+props.row.id)" v-if="canAdd" />
                  <q-btn color="grey" label="删除" @click="deleteDetail(props.row.id)"  v-if="canEdit|| props.row._owner" />
                </div>
                <q-item-label v-else-if="col.field === 'material_name'" class="flex items-center no-wrap">
                  <viewer :images="props.row.default_image" class="flex">
                    <template #default="scope">
                      <div class="image-box-xs" v-for="img in scope.images" :key="img.thumb">
                        <img class="fit-thumb" :src="img.image" :data-src="img.image" />
                      </div>
                    </template>
                  </viewer>
                  <div>{{ col.value }}</div>
                </q-item-label>
                <q-item-label v-else>{{ col.value }}</q-item-label>
              </q-item-section>
            </q-item>
            <q-item>
              <q-btn
                class="full-width"
                dense
                style="padding: 0;"
                :label="props.row._hidden ? '隐藏' : '更多'"
                :icon="props.row._hidden ? 'arrow_drop_up' : 'arrow_drop_down'"
                outline
                color="grey"
                @click="props.row._hidden = !props.row._hidden"
              />
            </q-item>
          </q-list>
        </template>
      </q-table>
    </template>
  </q-splitter>
</template>

<script>
import { defineComponent } from 'vue';
import searchArea from 'src/components/SearchArea.vue';
import { listPageMix } from 'src/lib/mixin.js';
import pageConfig from 'app/search/tenant/material/list.js';
import { useMeta } from 'quasar';
import { useStore } from 'stores/store';
import catalog from './catalog.vue';

export default defineComponent({
  name: 'materialList',
  setup (props, context) {
    const $store = useStore();
    const modelLabel = '货物档案';
    const moduleName = 'material';
    const submoduleName = 'list';
    const listApi = `/c2/tenant/${moduleName}/list`; // 数据列表接口
    const deleteApi = `/c2/tenant/${moduleName}/destroy`; // 删除接口

    useMeta({
      // 设置文件标题
      title: `${modelLabel}列表 - ${$store.siteConfig.appName} - 木多鱼系列`
    });

    return {
      modelLabel,
      moduleName,
      submoduleName,
      listApi,
      deleteApi
    }
  },
  components: {
    searchArea,
    catalog
  },
  mixins: [listPageMix],
  data () {
    return {
      columns: [
        { name: 'operate', label: '操作', align: 'center' },
        { name: 'sell', label: '上架', field: 'sell', sortable: true, align: 'center', format: val => val ? '上架' : '下架', classes: row => row.sell ? 'text-primary text-bold' : 'text-grey-8' },
        { name: 'recommend', label: '推荐', field: 'recommend', sortable: true, align: 'center' },
        { name: 'material_no', label: '货物编码', field: 'material_no', sortable: true, align: 'center' },
        { name: 'material_name', label: '货物名称', field: 'material_name', sortable: true, align: 'center' },
        { name: 'material_model', label: '货物规格', field: 'material_model', sortable: true, align: 'center' },
        { name: 'material_unit', label: '计量单位', field: 'material_unit', sortable: true, align: 'center', delay: true },
        { name: 'sale_price', label: '销售单价', field: 'sale_price', sortable: true, align: 'center', format: val => Number(val), delay: true },
        { name: 'material', label: '材质或色号', field: 'material', sortable: true, align: 'center', delay: true },
        { name: 'brand', label: '品牌', field: 'brand', sortable: true, align: 'center', delay: true },
        { name: 'origin', label: '产地', field: 'origin', sortable: true, align: 'center', delay: true },
        { name: 'barcode', label: '条码编号', field: 'barcode', sortable: true, align: 'center', delay: true },
        { name: 'remark', label: '备注', field: 'remark', sortable: true, align: 'center', delay: true },
        { name: 'pv', label: '浏览量', field: 'pv', sortable: true, align: 'center', delay: true },
        { name: 'catalog_name1', label: '一级分类', field: 'catalog_name1', align: 'center', delay: true },
        { name: 'catalog_name2', label: '二级分类', field: 'catalog_name2', align: 'center', delay: true },
        { name: 'catalog_name3', label: '三级分类', field: 'catalog_name3', align: 'center', delay: true },
        { name: 'catalog_name4', label: '四级分类', field: 'catalog_name4', align: 'center', delay: true },
        { name: 'create_date', label: '创建日期', field: 'create_date', align: 'center', delay: true },
        { name: 'create_user_name', label: '创建人', field: 'create_user_name', sortable: true, align: 'center', delay: true },
        { name: 'modify_date', label: '修改日期', field: 'modify_date', align: 'center', delay: true },
        { name: 'modify_user_name', label: '修改人', field: 'modify_user_name', sortable: true, align: 'center', delay: true }
      ],
      splitterModel: 30,
      catalogNode: null
    }
  },
  created () {
    this.assembly(pageConfig.search); // 根据配置生成搜索条件
    this.searchList.catalog_id = { value: '' };
    this.$storage.get(`${this.moduleName}-${this.submoduleName}-splitter`).then(param => {
      if (param) {
        this.splitterModel = param;
      }
    });
  },
  mounted () {
    let query = null, locateId = null;
    if (this.$route.query.back === 'true' && this.searchParam[this.pageKeyWord]) {
      query = this.searchParam[this.pageKeyWord].query || {};
      for (let i = 4; i > 0; i--) {
        if (query[`c${i}`]) {
          locateId = query[`c${i}`];
          break;
        }
      }
    }
    this.$refs.catalog.refresh(locateId, query);
  },
  methods: {
    selectCatalog (node) {
      if (node && node.parent_id > 0) {
        this.searchList.catalog_id.value = node.id;
        this.catalogNode = node;
      } else {
        this.searchList.catalog_id.value = null;
        this.catalogNode = null;
      }
    },
    goDetailEx (id) {
      const query = {
        c1: '',
        c2: '',
        c3: '',
        c4: ''
      };
      const ids = String(id).split(',');
      if (ids.length > 1 && ids[0] < 0) { // 克隆
        const oriNode = this.data.filter(v => v.id == ids[1]);
        if (oriNode.length > 0) {
          for (let i = 1; i <= 4; i++) {
            query[`c${i}`] = oriNode[0][`catalog_id${i}`] || '';
          }
        }
      } else if (this.catalogNode) {
        let node = this.catalogNode;

        while (node.levels > 1) {
          query[`c${node.levels - 1}`] = node.id;
          node = this.$refs.catalog.getNode(node.parent_id);
        }
      }

      this.goDetail(id, query);
    },
    doImport () {
      let query = null;

      if (this.catalogNode) {
        let node = this.catalogNode;
        query = {};

        while (node.levels > 1) {
          query[`c${node.levels - 1}`] = node.id;
          node = this.$refs.catalog.getNode(node.parent_id);
        }
      }

      const para = {};
      const route = { path: '/main/' + this.moduleName + '/import' };

      para[this.pageKeyWord] = {
        pagination: this.pagination,
        filter: this.filter
      };
      if (query) {
        para[this.pageKeyWord].query = query;
        route.query = query;
      }

      this.saveSearchParam(para);
      this.saveScrollTop();

      this.$router.push(route);
    }
  },
  computed: {
    canAdd () {
      return this.rights[this.moduleName] && this.rights[this.moduleName].add;
    },
    canEdit () {
      return this.rights[this.moduleName] && this.rights[this.moduleName].edit;
    }
  },
  watch: {
    splitterModel (val) {
      this.$storage.set(`${this.moduleName}-${this.submoduleName}-splitter`);
    }
  }
});
</script>
